package com.example.adapter_sdk.quick;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.ListUpdateCallback;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

public abstract class BaseQuickAdapter<T> extends RecyclerView.Adapter<BaseViewHolder> {
    private List<T> data = new ArrayList<>();
    private int layoutId;//关联的item布局id
    private int positions;
    private int counts;
    private static final int HEADERTYPE = -1;
    private static final int FOOTTYPE = -2;
    private static final int CONTENTTYPE = 0;
    private int count = 0;
    //头布局viewholder
    private HeaderViewHolder headerViewHolder;
    //脚布局viewholder
    private FoodViewHolder foodViewHolder;
    //item点击监听器
    private OnItemClickListener onItemClickListener;
    //子控件的监听器
    private OnItemClickChildListener onItemClickChildListener;


    //全部子控件添加集合
    private List<Integer> ids = new ArrayList<>();

    //添加子控件监听方法
    protected void addItemChildClick(int... id) {
        for (int i = 0; i < id.length; i++) {
            ids.add(id[i]);
        }
    }

    public void setOnItemClickChildListener(OnItemClickChildListener onItemClickChildListener) {
        this.onItemClickChildListener = onItemClickChildListener;
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    private void bindListener(BaseViewHolder holder) {
        if (onItemClickListener != null)
            holder.itemView.setOnClickListener(v -> {
                onItemClickListener.onItemClick(this,holder.getAdapterPosition()-(headerViewHolder == null?0:1));
            });
        if (onItemClickChildListener != null)
            for (Integer id : ids) {
                holder.getView(id).setOnClickListener(v->{
                    onItemClickChildListener.onItemClickChild(this,id,holder.getAdapterPosition()-(headerViewHolder == null?0:1));
                });
            }
    }

    @Override
    public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
        RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
        if (manager instanceof GridLayoutManager) {
            //合并
            GridLayoutManager gridLayoutManager = (GridLayoutManager) manager;
            gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int position) {
                    if (position == 0 && headerViewHolder != null)
                        return gridLayoutManager.getSpanCount();
                    if (position == (getItemCount() - 1) && foodViewHolder != null)
                        return gridLayoutManager.getSpanCount();
                    return 1;
                }
            });
        }
    }

    public BaseQuickAdapter(int layoutId) {
        this.layoutId = layoutId;
    }

    public List<T> getData() {
        return data;
    }

    //设置头布局方法  存在多个头布局情况
    public void setHeaderView(View headerView) {
        if (headerViewHolder == null) {
            LinearLayout linearLayout = new LinearLayout(headerView.getContext());
            linearLayout.setOrientation(LinearLayout.VERTICAL);
            ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            linearLayout.setLayoutParams(layoutParams);
            headerViewHolder = new HeaderViewHolder(linearLayout);
            count += 1;
        }
        headerViewHolder.rootView.addView(headerView);
    }

    //设置脚布局方法
    public void setFootView(View footView) {
        if (foodViewHolder == null) {
            LinearLayout linearLayout = new LinearLayout(footView.getContext());
            linearLayout.setOrientation(LinearLayout.VERTICAL);
            ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            linearLayout.setLayoutParams(layoutParams);
            foodViewHolder = new FoodViewHolder(linearLayout);
            count += 1;
        }
        foodViewHolder.rootView.addView(footView);
    }

    //添加一条数据源
    public void add(T entity) {
        data.add(entity);
        notifyItemInserted(data.size() - 1);
    }

    //添加多条数据源
    public void adds(List<T> list) {
        if (list == null)
            return;
        if (list.size() == 0)
            return;
        int position = data.size() - 1;
        data.addAll(list);
        notifyItemRangeChanged(position, data.size() - 1);
    }

    //删除一条数据源
    public void remove(int position) {
        if (position < 0 || position >= data.size())
            return;
        data.remove(position);
        notifyItemRemoved(position);
    }

    //设置新的数据源  又去当前方法设计到适配器下拉刷新逻辑  整体使用diffutil进行数据比对后刷新
    public void setNewInstance(List<T> list) {
        if (data.size() == 0) {
            data.addAll(list);
            notifyDataSetChanged();
            return;
        }
        DiffUtil.DiffResult result = DiffUtil.calculateDiff(new BaseQuickDiff<>(data, list));
        result.dispatchUpdatesTo(new ListUpdateCallback() {
            @Override
            public void onInserted(int position, int count) {
                Log.i("hxw1","onInserted"+position+count);
                List<T> datas = list.subList(position, count);
                data.addAll(position, datas);
                positions = position;
                counts = count;
            }

            @Override
            public void onRemoved(int position, int count) {
                Log.i("hxw1","onRemoved"+position+count);
                int i = position + count - 1;
                for (; i >= position; i--) {
                    data.remove(i);
                }
            }

            @Override
            public void onMoved(int fromPosition, int toPosition) {
                Log.i("hxw1","onMoved"+fromPosition+toPosition);
            }

            @Override
            public void onChanged(int position, int count, @Nullable Object payload) {
                Log.i("hxw1","onChanged"+position+count);
                onRemoved(position, count);
                onInserted(position, count);
            }
        });
        Log.i("hxw1","onInserted"+positions+counts);
        notifyItemRangeChanged(positions, counts + (headerViewHolder == null ? 0 : 1));
    }

    public abstract void convert(BaseViewHolder holder, T item);

    @NonNull
    @Override
    public BaseViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        if (viewType == HEADERTYPE) {
            return headerViewHolder;
        } else if (viewType == FOOTTYPE) {
            return foodViewHolder;
        }
        View itemView = LayoutInflater.from(parent.getContext()).inflate(layoutId, parent, false);
        BaseViewHolder baseViewHolder = new BaseViewHolder(itemView);
        bindListener(baseViewHolder);
        return baseViewHolder;
    }

    //区分列表头布局以及脚布局
    @Override
    public int getItemViewType(int position) {
        if (position == 0 && headerViewHolder != null)
            return HEADERTYPE;
        else if (position == (getItemCount() - 1) && foodViewHolder != null)
            return FOOTTYPE;
        return CONTENTTYPE;
    }

    @Override
    public void onBindViewHolder(@NonNull BaseViewHolder holder, int position) {
        if (holder instanceof HeaderViewHolder || holder instanceof FoodViewHolder)
            return;
        T item = data.get(position - (headerViewHolder == null ? 0 : 1));
        convert(holder, item);
    }

    @Override
    public int getItemCount() {
        return data.size() + count;//由于添加头布局以及脚布局问题  需要在原有数据源的基础长度添加出头布局和脚布局数量
    }

    //item点击监听回调
    public interface OnItemClickListener {
        void onItemClick(RecyclerView.Adapter adapter, int position);
    }

    //itemchild监听回调
    public interface OnItemClickChildListener {
        void onItemClickChild(RecyclerView.Adapter adapter, int id, int position);
    }
}
